package org.groupg.practice;

import org.jgroups.*;
import org.jgroups.util.Util;

public class SimpleChat implements Receiver {
    private JChannel channel;
    private String user;

    public static void main(String[] args) throws Exception {
        new SimpleChat().start();
    }

    private void start() throws Exception {
        channel = new JChannel(); // 使用默认配置
        channel.setReceiver(this);
        channel.connect("ChatCluster");

        user = System.getProperty("user.name", "n/a");
        eventLoop();
        channel.close();
    }

    private void eventLoop() {
        while (true) {
            try {
                String line = Util.readStringFromStdin("> ");
                if (line.startsWith("quit") || line.startsWith("exit")) {
                    break;
                }
                Message msg = new ObjectMessage();
                msg.setObject(user + ": " + line);
                channel.send(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void receive(Message msg) {
        System.out.println(msg.getSrc() + ": " + msg.getObject());
    }

    @Override
    public void viewAccepted(View view) {
        System.out.println("** View: " + view);
    }
}
